/* 
 * File:   tcp_time_server.cpp
 * Author: walter_2
 *
 * Created on 2011-11-22, 8:59 P.M.
 */

#include	<sys/types.h>	/* basic system data types */
#include	<sys/socket.h>	/* basic socket definitions */
#include	<sys/time.h>	/* timeval{} for select() */
#include	<time.h>		/* timespec{} for pselect() */
#include	<netinet/in.h>	/* sockaddr_in{} and other Internet defns */
#include	<arpa/inet.h>	/* inet(3) functions */
#include	<errno.h>
#include	<fcntl.h>		/* for nonblocking */
#include	<netdb.h>
#include	<signal.h>
#include	<stdio.h>
#include	<stdlib.h>
#include	<string.h>
#include	<sys/stat.h>	/* for S_xxx file mode constants */
#include	<sys/uio.h>		/* for iovec{} and readv/writev */
#include	<unistd.h>
#include	<sys/wait.h>
#include	<sys/un.h>		/* for Unix domain sockets */

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define	LISTENQ		1024	/* 2nd argument to listen() */

/* Miscellaneous constants */
#define	MAXLINE		4096	/* max text line length */
#define	MAXSOCKADDR     128	/* max socket address structure size */
#define	BUFFSIZE	8192	/* buffer size for reads and writes */

#define	SA	struct sockaddr

/* default file access permissions for new files */
#define	FILE_MODE	(S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)

/* default permissions for new directories */
#define	DIR_MODE	(FILE_MODE | S_IXUSR | S_IXGRP | S_IXOTH)

typedef	void	Sigfunc(int);	/* for signal handlers */

using namespace std;

/*
 * 
 */
int main(int argc, char** argv) {
    int listenfd, connfd;
    struct sockaddr_in servaddr;
    char buff[MAXLINE];
    
    time_t ticks;
    
    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    if(listenfd < 0) {
        fprintf(stderr, "socket error");
        return -1;
    }
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(13);
    int ret = bind(listenfd, (SA *)&servaddr, sizeof(servaddr));
    if( ret < 0) {
        fprintf(stderr, "bind error");
        return -1;
    }
    ret = listen(listenfd, LISTENQ);
    if(ret < 0) {
        fprintf(stderr, "listen error");
        return -1;
    }
    
    for(;;) {
        connfd = accept(listenfd, (SA *)NULL, NULL);
        if(connfd < 0) {
            fprintf(stderr, "accept error");
            return -1;
        }
        ticks = time(NULL);
        snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));
        int count = write(connfd, buff, strlen(buff));
        if(((size_t)count) != strlen(buff)) {
            fprintf(stderr, "write error");
            return -1;
        }
    }
    return 0;
}

